<template>
  <!-- 《其他》 -->
  <div class="tables" v-loading="loading">
    <scoreDialog
      :courseId="scoreDialogForm.courseId"
      :courseType="scoreDialogForm.courseType"
      :open.sync="scoreDialog_open"
      type="detail"
    ></scoreDialog>
    <!-- 搜索项 -->
    <div class="search_bar flexBet">
      <div class="greenText">
        班级平均分 :{{ avgScore > 0 ? avgScore.toFixed(2) : avgScore }}
      </div>

      <div class="inputs flex">
        <div class="label">学生</div>
        <el-input
          style="width: 180px"
          class="inputstyle"
          v-model="queryParams.search"
          placeholder="请输入学生姓名/学号"
          clearable
          @keyup.enter.native="queryParamsSearch"
          @clear="queryParamsSearch"
        />
        <div class="label" style="margin-left: 24px">作业</div>
        <!-- <el-input
          style="width: 180px"
          class="inputstyle"
          v-model="queryParams.examName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="queryParamsSearch"
        /> -->
        <el-cascader
          v-model="queryParams.indexId"
          :options="courseIndexTree"
          filterable
          clearable
          :props="{
            expandTrigger: 'hover',
            checkStrictly: true,
            value: 'id',
            label: 'name',
          }"
          @change="queryParamsSearch"
        />
        <div
          class="primaryBorderBtn w88"
          style="margin-left: 24px"
          @click="queryParamsSearch"
        >
          搜索
        </div>

        <div
          class="normalBtn w88"
          @click="resetQueryParamsSearch"
          style="margin-left: 12px"
        >
          重置
        </div>
      </div>
    </div>
    <div class="search-tip">注：统计数据已折算为百分制</div>
    <div class="search_bar flex">
      <div class="normalBtn w114" @click="handleExport">
        <svg-icon class-name="icon-img" icon-class="download_svg"/>
        导出作业
      </div>
      <div
        class="normalBtn w114"
        style="margin-left: 17px"
        @click="scoreDetail()"
      >
        <svg-icon class-name="icon-img" icon-class="score_svg"/>
        配分表
      </div>
    </div>
    <div v-if="labels.length == 0">
      <el-empty description="暂无数据~"></el-empty>
    </div>
    <div
      v-else
      :class="['data_table', list.length > 0 ? '' : 'nodata_table', 'rela']"
      style="margin-top: 16px; height: calc(100vh - 220px)"
    >
      <el-table
        border
        :summary-method="getSummaries"
        v-loading="loading"
        :data="list"
        height="100%"
        @cell-click="cellclick"
      >
        <el-table-column
          fixed="left"
          label="章节"
          width="180"
          align="center"
          prop="indexName"
        >
          <!-- 编辑表头 -->
          <template slot="header">
            <!-- 章节 -->

            <div class="rectangle_contian rela">
              <div class="rectangle absolute"></div>
              <div class="rectangle_chapter">学生</div>
              <div class="rectangle_student">内容</div>
            </div>
            <div class="rectangle_sumlabel">总得分</div>
          </template>
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.indexName"
              placement="top"
              :open-delay="300"
            >
              <span style="cursor: pointer">{{
                  filterTxt(scope.row.indexName)
                }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in labels"
          :key="index"
          show-overflow-tooltip
          :label="item.name"
          align="center"
          :prop="item.t"
          :width="labels.length > 6 ? 100 : 'auto'"
        >
          <template slot="header">
            <div>{{ item.name }}</div>
            <div>{{ item.studentNum }}</div>
            <div class="rectangle_sum">{{ item.sum }}</div>
          </template>
          <template slot-scope="scope">
            <div
              :class="[
                scope.row[item.t].score > -1 ? 'bottomLine' : '',
                'shou',
              ]"
            >
              {{ scope.row[item.t].score }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column
          show-overflow-tooltip
          label="操作"
          fixed="right"
          align="center"
          prop="branchName"
          width="100"
        >
          <template slot="header">
            <div class="rectangle_operate">操作</div>
            <div
              class="rectangle_statistics rectangle_sum shou"
              @click.stop="handleDetail('all')"
            >
              统计
            </div>
          </template>
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleDetail(scope.row, scope.$index)"
            >统计
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <!-- <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    <!-- 试卷详情 -->
    <el-drawer
      :with-header="false"
      :visible.sync="showExam"
      size="700px"
      direction="rtl"
      :before-close="exam_handleClose"
    >
      <examination-answer
        inHeight="calc(100vh - 165px)"
        :showStatus="false"
        ref="examination"
        :loading="loading"
        :examInfo="examInfo"
        :titleName="titleName"
        :endTime="null"
      >
        <div class="drawer-content" style="padding: 6px 0 0 22px">
          <div class="drawer-content-info">
            <div>
              <div class="drawer-content-item flex">
                内&nbsp;&nbsp;容：
                <tooltip
                  width="545"
                  class="overTxt"
                  :text="`${row.taskInfo}`"
                ></tooltip>
              </div>
            </div>
            <div class="flexBet">
              <div class="drawer-content-item w295 flex">
                学&nbsp;&nbsp;生：
                <tooltip
                  width="210"
                  class="overTxt"
                  :text="`${row.name} (${row.studentNum})`"
                ></tooltip>
              </div>
              <div class="drawer-content-item w295 flex">
                行政班：
                <tooltip
                  width="210"
                  class="overTxt"
                  :text="`${row.className}`"
                ></tooltip>
              </div>
            </div>
          </div>
        </div>
      </examination-answer>
    </el-drawer>
    <!-- 详情抽屉 -->
    <el-drawer
      :with-header="false"
      :visible.sync="showDrawer"
      size="700px"
      direction="rtl"
      :before-close="drawer_handleClose"
    >
      <div style="height: 100vh" class="rela">
        <div class="drawer-title flexBet">
          <div class="t1">作业统计</div>
          <div class="t2" v-if="chartDate.ancestorsName">
            总分: {{ chartDate.totalScore }}分
          </div>
        </div>
        <div class="drawer-content">
          <div class="drawer-content-info">
            <div v-if="chartDate.ancestorsName">
              <div class="drawer-content-item flex">
                内&nbsp;&nbsp;容：
                <tooltip
                  width="545"
                  class="overTxt"
                  :text="`${chartDate.ancestorsName}`"
                ></tooltip>
              </div>
            </div>
            <div class="flexBet">
              <div class="drawer-content-item w295 flex">
                授课班级：
                <tooltip
                  width="210"
                  class="overTxt"
                  :text="`${scoreDialogForm.schedulingName}`"
                ></tooltip>
              </div>
              <div class="drawer-content-item w295 flex">
                平均分：
                <div class="overTxt">{{ chartDate.avgScore }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex drawer-chart rela">
          <div style="" class="chart" ref="chart"></div>
        </div>
        <div class="search_bar flexEnd absolute" style="bottom: 56px">
          <div
            class="normalBtn w88"
            @click="showDrawer = false"
            style="margin-right: 56px"
          >
            关 闭
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getPost_student } from '@/api/schoolOrganization/student'
import scoreDialog from '@/views/tea_course/components/scoreDialog'
import { classIndexScoreList, classIndexScore } from '@/api/tea_studentGrade/usual'
import examinationAnswer from '@/views/home/components/examinationAnswer'
import { getExamPaperApi } from '@/api/ExaminationModule/exam'
import * as echarts from 'echarts'
import { formatDate } from '@/utils'
import { getCourseIndexTree, getDistributionList } from '@/api/course/course'

export default {
  components: {
    examinationAnswer,
    scoreDialog
  },
  props: {
    activeName: {
      type: String
    },
    courseInfo: Object
  },
  data() {
    return {
      avgScore: 0,
      examInfo: {},
      titleName: '作业详情',
      list: [],
      loading: false,
      // 总条数
      total: 3,
      // 搜索条件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: '',
        examName: '',
        indexId: ''
      },
      showExam: false,
      showDrawer: false,
      drawer_scoreRecordList: [],
      drawer_row: {},
      row: {},
      labels: [],
      scoreDialogForm: {},
      chartDate: '',
      scoreDialog_open: false,
      courseIndexTree: []
    }
  },
  watch: {
    activeName: {
      handler(newValue) {
        console.log(newValue)
        if (newValue == 'normal_homework') {
          this.getList()
          this.refreshCategoryTree()
        }
      },
      immediate: true // 这个选项确保handler在watcher被创建时立即调用
    }
  },
  mounted() {
    this.scoreDialogForm = JSON.parse(localStorage.getItem('COURSE_INFO'))
  },
  methods: {
    filterTxt(input) {
      const fields = input.split('/')
      let txt = ''
      if (fields.length > 3) {
        const secondField = fields[1] // 第二个字段
        const lastField =
          fields[fields.length - 1].length > 10
            ? fields[fields.length - 1].substring(0, 10) + '...'
            : fields[fields.length - 1]

        // 如果第二个字段的长度大于10，则截短并在末尾添加省略号
        if (secondField.length > 10) {
          fields[1] = secondField.substring(0, 10) + '...'
          txt = `${fields[0]}/${fields[1]}/${lastField}`
        } else {
          txt = `${fields[0]}/${fields[1]}/.../${lastField}`
        }
      } else {
        txt =
          fields.length > 2
            ? `${fields[0]}/${fields[1]}/${fields[2]}`
            : `${fields[0]}/${fields[1]}`
      }

      return txt
    },
    scoreDetail() {
      this.scoreDialog_open = true
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          // 第一列显示“合计”
          sums[index] = '总得分'
          return
        }
        if (index == columns.length - 1) {
          sums[index] = ''
          return
        }

        // 获取当前列的数据并转换为数字
        const values = data.map((item) => {
          return item[column.property].sumScore - 0
        })
        // 过滤掉无效值（NaN）
        const validValues = values.filter((item) => !Number.isNaN(item))
        if (validValues.length > 0) {
          // 计算总和
          // 计算平均值（只除以有数据的数量）
          const average = validValues.reduce((prev, curr) => prev + curr, 0)

          // 显示平均值
          sums[index] = average.toFixed(2) // 保留两位小数
        } else {
          // 如果所有数据都为空，显示空
          sums[index] = ''
        }
      })

      return sums
    },
    //递归向courseIndexTree中增加level和 selectIds:[] 属性
    formatTreeData(data, level = 0, selectIds = []) {
      return data.map((item) => {
        const newItem = { ...item, level, selectIds } // 添加 level 属性
        if (newItem.children && newItem.children.length > 0) {
          newItem.children = this.formatTreeData(
            newItem.children,
            level + 1,
            []
          ) // 递归处理子节点
        }
        return newItem
      })
    },
    // 刷新分类树
    async refreshCategoryTree() {
      console.log('刷新分类树')
      let res = await getCourseIndexTree(
        JSON.parse(localStorage.getItem('COURSE_INFO')).courseId
      )
      const { code, data } = res
      if (code == 200) {
        this.courseIndexTree = this.formatTreeData([data])
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.labels.length == 0) {
        // 暂无数据
        this.$message({
          message: '暂无数据',
          type: 'warning'
        })
        return
      }
      this.download(
        `/school/teacher/teachingPage/exportClassIndexScoreList/${
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId
        }`,
        { ...this.queryParams, type: 2 },
        `《${this.courseInfo.courseName}》${
          this.courseInfo.schedulingName
        }课后作业导出表_${new Date().getTime()}.xlsx`
      )
    },

    async cellclick(row, column) {
      this.row = row
      try {
        let params_cell = {}
        for (let i = 0; i < this.labels.length; i++) {
          if (this.labels[i].t == column.property) {
            params_cell = row.student[i]
            if (params_cell.examPaperId && params_cell.score) {
              this.showExam = true
              this.getExaminationAnswerList(params_cell, 'exam')
            }
          }
        }
      } finally {
      }
    },

    // 获取试卷详情
    async getExaminationAnswerList(row, type) {
      this.loading = true
      try {
        let studentId = row.studentId
        let id = type == 'exam' ? row.examPaperId : row.homeworkPaperId
        let params = {
          studentId: studentId
        }
        let res = await getExamPaperApi(id, params)
        let stuRes = await getPost_student(studentId)
        this.row.className = stuRes.data.className
        this.row.name = stuRes.data.name
        this.row.studentNum = stuRes.data.studentNum
        const { code, data } = res
        if (code == 200) {
          this.row.taskInfo = data.taskInfo
          this.examInfo = data.ccExamPaper
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    // 抽屉-关闭
    exam_handleClose() {
      this.showExam = false
    },
    drawer_handleClose() {
      this.showDrawer = false
    },
    // 详情打开-抽屉
    handleDetail(row, index) {
      console.log(row)
      this.rowIndex = index
      this.row = row
      this.showDrawer = true

      //   加载表格
      this.getDrawerList()
    },

    // 抽屉-获取打分记录
    async getDrawerList() {
      this.loading = true
      try {
        let res = await classIndexScore(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId,
          { indexId: this.row.indexId, type: 2 }
        )
        const { code, data } = res
        if (code == 200) {
          this.chartDate = data
          //   渲染图标
          this.$nextTick(() => {
            this.setOptionCdn()
          })
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 搜索按钮
    queryParamsSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 检索表单重置
    resetQueryParamsSearch() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        search: '',
        examName: '',
        indexId: ''
      }
      this.queryParamsSearch()
    },

    async getList() {
      this.loading = true
      try {
        let params = JSON.parse(JSON.stringify(this.queryParams))
        params.indexId = params.indexId[params.indexId.length - 1]
        let res = await classIndexScoreList(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId,
          { ...params, type: 2 }
        )
        let scoreRes = await getDistributionList(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseId
        )
        const { code, data } = res
        if (code == 200) {
          // 用于循环表头
          let labels = []
          for (let i = 0; i < data.list.length; i++) {
            for (let j = 0; j < data.list[i].student.length; j++) {
              // 获取labels只需要循环一次
              if (i == 0) {
                labels.push({
                  t: `lable${data.list[i].student[j].studentId}`,
                  name: data.list[i].student[j].name,
                  studentNum: data.list[i].student[j].studentNum
                })
              }
            }
          }
          // 用于获取表数据
          // 结构类似于{stuName:xxx,label1:'正常',label2:'迟到'}
          for (let i = 0; i < data.list.length; i++) {
            let scorePercentage = 0
            for (
              let h = 0;
              h < scoreRes.data.homeworkCourseIndexScoreEntityList.length;
              h++
            ) {
              if (
                scoreRes.data.homeworkCourseIndexScoreEntityList[h].id ==
                data.list[i].indexId
              ) {
                scorePercentage =
                  scoreRes.data.homeworkCourseIndexScoreEntityList[h]
                    .homeworkScorePercentage
              }
            }
            for (let j = 0; j < data.list[i].student.length; j++) {
              data.list[i].scorePercentage = scorePercentage

              data.list[i][`${labels[j].t}`] = {
                score:
                  data.list[i].student[j].score ||
                  data.list[i].student[j].score == 0
                    ? data.list[i].student[j].score
                    : '--',
                sumScore:
                  data.list[i].student[j].score > 0
                    ? (
                      (data.list[i].student[j].score * scorePercentage) /
                      100
                    ).toFixed(2)
                    : data.list[i].student[j].score
              }
              data.list[i].studentId = data.list[i].student[j].studentId
              data.list[i].name = data.list[i].student[j].name
              data.list[i].studentNum = data.list[i].student[j].studentNum
              data.list[i].examPaperId = data.list[i].student[j].examPaperId
              data.list[i].homeworkPaperId =
                data.list[i].student[j].homeworkPaperId
            }
          }
          this.avgScore = data.avgScore
          this.list = data.list
          // 遍历获取总得分
          for (let i = 0; i < labels.length; i++) {
            let sum = 0
            let notStart = 0
            for (let j = 0; j < data.list.length; j++) {
              if (data.list[j][labels[i].t].sumScore != '-') {
                sum += data.list[j][labels[i].t].sumScore - 0
              } else {
                notStart++
              }
            }
            labels[i].sum = notStart == data.list.length ? '-' : sum.toFixed(2)
          }
          this.labels = labels
          console.log('list', this.list, labels)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 导出
    async confirmexport(str) {
      let obj = this.queryParams
      obj.params = str
      this.download(
        `/school/system/exportData/courseConstructionExport`,
        obj,
        `课程建设情况表_${formatDate(new Date())}.xlsx`
      )
    },

    // 抽屉-图表生成
    setOptionCdn() {
      let myChart = echarts.init(this.$refs.chart)
      let option
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [
              '0~60(不包含)',
              '60~70(不包含)',
              '70~80(不包含)',
              '80~90(不包含)',
              '90~100'
            ],
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '数据',
            type: 'bar',
            barWidth: '60%',
            data: [
              this.chartDate.failNum,
              this.chartDate.passNum,
              this.chartDate.generallyNum,
              this.chartDate.goodNum,
              this.chartDate.excellentNum
            ]
          }
        ]
      }
      option && myChart.setOption(option)
    }
  }
}
</script>
<style scoped lang="scss">
.tables {
  height: calc(100vh - 220px) !important;
  box-sizing: border-box;
  overflow-y: auto;
  padding: 0 24px;
  margin: 16px 0;
  width: 100%;
}

::v-deep.container .exam_content .exam_list {
  padding: 32px 40px !important;
}

::v-deep .el-table th.el-table__cell > .cell {
  padding: 0 !important;
}

::v-deep .el-table tr th {
  min-width: 90px !important;
}

.bottomLine {
  text-decoration: underline;
}

.rectangle_chapter {
  position: absolute;
  top: 5px;
  right: 23px;
  z-index: 100;
  color: #515a6e;
  font-size: 13px;
}

.rectangle_contian {
  height: 59px;
}

.rectangle_operate {
  height: 46px;
  line-height: 46px;
}

.rectangle_statistics {
  font-size: 12px;
  font-weight: 400;
  color: #11a983;
}

.rectangle_sumlabel {
  margin-top: 2px;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

.rectangle_sum {
  padding-top: 8px;
  margin-top: 5px;
  border-top: 1px solid #ebeef5;
}

.rectangle_student {
  position: absolute;
  bottom: 4px;
  left: 34px;
  z-index: 100;
  color: #515a6e;
  font-size: 13px;
}

::v-deep .el-table tr th:nth-of-type(1) {
  padding: 0 !important;

  .cell {
    height: 100%;
  }
}

.rectangle {
  border-radius: 10px 0 0 0;
  background: #f8f8f9;
  top: 1px;
  left: 1px;
  z-index: 10;
  width: 179px; /* 设置宽度 */
  height: 100%; /* 设置高度 */
  overflow: hidden; /* 确保对角线不会超出容器 */
}

.rectangle::before {
  border: 1px solid #dfe6ec;
  content: "";
  position: absolute;
  top: 66px;
  left: -150px; /* 从左外侧开始 */
  width: 600px; /* 对角线长度，需足够长以跨越整个矩形 */
  height: 600px; /* 对角线长度 */
  background: linear-gradient(
      to bottom right,
      transparent 49.5%,
      red 49.5%,
      red 50.5%,
      transparent 50.5%
  ); /* 创建对角线 */
  transform: rotate(-72deg); /* 旋转以形成对角线 */
}

::v-deep .el-table__footer-wrapper {
  tr {
    .el-table__cell:last-of-type {
      color: #11a983;
      font-size: 12px !important;
    }
  }
}

.greenText {
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 500;
  font-size: 14px;
  color: #28b28b;
  text-align: left;
  font-style: normal;
}

::v-deep .container {
  padding: 0 !important;

  .exam_content {
    height: 100vh !important;
  }
}

.w88 {
  width: 88px;
}

.w114 {
  width: 114px;
}

.search-tip {
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  line-height: 20px;
  font-style: normal;
  margin: 20px 0 16px 0;
}

.w124 {
  width: 124px;
}

.drawer-chart {
  margin-left: 55px;
  margin-top: 48px;
  width: 589px;
  height: 368px;

  .chart {
    width: 589px;
    height: 368px;
  }

  .chartsTip {
    top: 0;
    right: 0;
  }
}

.drawer-content {
  padding: 6px 0 0 32px;
}

.drawer-content-info {
  background-image: url("../../../assets/images/scoreBg2.png");
  background-size: 648px 86px;
  width: 648px;
  height: 86px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 8px;

  .w295 {
    width: 295px;
  }

  .drawer-content-item {
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #788295;
    line-height: 22px;
    text-align: left;
    font-style: normal;
    margin: 0 0 0 24px;
    padding: 7px 0;

    div {
      width: 210px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 16px;
      color: #333333;
      line-height: 22px;
      text-align: left;
      font-style: normal;
    }
  }
}

.drawer-title {
  box-sizing: border-box;
  height: 70px;
  border-bottom: 1px solid #edeff0;
  padding: 0 32px;

  .t1 {
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 600;
    font-size: 18px;
    color: #333333;
    line-height: 70px;
    text-align: left;
    font-style: normal;
  }

  .t2 {
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    line-height: 70px;
    font-style: normal;
  }
}

.exportbtn {
  display: flex;
  justify-content: space-between;

  margin: 10px 0;
}

// ::v-deep .el-table__body-wrapper {
//   max-height: calc(100vh - 330px - 86px) !important;
// }

// ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
//   -webkit-appearance: none;
//   background-color: #fff;
//   /* 滚动条背景颜色 */
//   height: 8px;
//   /* 滚动条高度 */
// }

// ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
//   border-radius: 4px;
//   background-color: #bfbfbf;
// }

// ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
//   background-color: #fff;
// }
</style>
